<?php
namespace app\controller\merchant\store\product;
use app\common\model\store\StoreCategory;
use app\common\model\system\merchant\MerchantCategoryIntention;
use app\common\repositories\store\product\ProductCopyRepository;
use app\common\dao\store\StoreCategoryDao;
use app\common\repositories\store\StoreCategoryRepository;
use app\common\repositories\system\merchant\MerchantCategoryIntentionRepository;
use app\common\repositories\system\serve\ServeOrderRepository;
use app\validate\merchant\MerchantCategoryIntentionValidate;
use crmeb\basic\BaseController;
use think\App;
use think\db\exception\DbException;
use think\exception\ValidateException;

class CategoryIntention extends BaseController
{
    /**
     * @var MerchantCategoryIntentionRepository
     */
    protected $repository;

    /**
     * CategoryIntention constructor.
     * @param App $app
     * @param MerchantCategoryIntentionRepository $repository
     */
    public function __construct(App $app, MerchantCategoryIntentionRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }
    /**
     * @return mixed
     * @author: fupeng
     * @day: 2023/10/17
     */
    public function lst()
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['keyword', 'date', 'status']);
        return app('json')->success($this->repository->merLst($this->request->merId(), $where, $page, $limit));
    }

    /**
     * @return mixed
     * @author: fupeng
     * @day: 2023/10/17
     */
    public function getStatusFilter()
    {
        return app('json')->success($this->repository->getFilter($this->request->merId()));
    }

    /**
     * @param MerchantCategoryIntentionValidate $validate
     * @return mixed
     * @author: fupeng
     * @day: 2023/10/17
     */
    public function create(MerchantCategoryIntentionValidate $validate)
    {
        $data = $this->checkParams($validate);
        $info = $this->repository->getWhere(['mer_id'=>$this->request->merId(),'status'=>0]);
        if($info)
            throw new ValidateException('您好，您提交的类目正在审核中，请在审核通过后在提交');
        $info = $this->repository->getWhere(['mer_id'=>$this->request->merId(),'status'=>1,'lvl_two'=>$data['lvl_two']]);
        if($info)
            throw new ValidateException('您已经申请过改类目，请勿重新提交');
        $data['mer_id'] = $this->request->merId();
        $this->repository->create($data);
        return app('json')->success('添加成功');
    }


    /**
     * @param $id
     * @param MerchantCategoryIntentionValidate $validate
     * @return mixed
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: fupeng
     * @day: 2023/10/17
     */
    public function update($id, MerchantCategoryIntentionValidate $validate)
    {
        $data = $this->checkParams($validate);
        $getOne = $this->repository->getWhere(['mer_category_intention_id' => $id,'mer_id' => $this->request->merId()]);
        if (!$getOne) return app('json')->fail('数据不存在');

        if($getOne->status == 0){
            return app('json')->fail('已提交，请勿重复提交');
        }
        $select = $this->repository->selectWhere([
                ['mer_id','=',$this->request->merId()],
                ['status','=',0],
                ['mer_category_intention_id','<>',$id]
            ]
        );
        if(count($select) >0)
            throw new ValidateException('您好，您提交的类目正在审核中，请在审核通过后在编辑');
        $data['status'] = 0;
        $this->repository->update($id, $data);
        return app('json')->success('编辑成功');
    }


    /**
     * 撤回
     * @param $id
     * @return mixed
     * @author: fupeng
     * @day: 2023/10/17
     */
    public function retract($id)
    {
        $info = $this->repository->getWhere(['mer_id'=>$this->request->merId(),'mer_category_intention_id'=>$id]);
        if (!$info)
            return app('json')->fail('数据不存在');
        if($info->status != 0)
            return app('json')->fail('该数据不能撤回');

        $data['status'] = 3;
        $this->repository->update($id, $data);
        return app('json')->success('撤回成功');
    }


    /**
     * @param StoreCategoryRepository $repository
     * @return mixed
     * @author: fupeng
     * @day: 2023/10/17
     */
    public function getCategorylst(StoreCategoryDao $dao)
    {
        $Bind =  (new MerchantCategoryIntention())->where(['mer_id'=>$this->request->merId(),'is_del'=>0,'status'=>1])->select()->toArray();
        $bindList = array_column($Bind,'lvl_two');
        $list2 = (new StoreCategory())
            ->field('store_category_id,pid,cate_name,margin,commission_rate')
            ->where(['type'=>0,'is_show'=>1])
            ->select()->toArray();
        foreach ($list2 as &$v){
            $v['disabled'] = false;
            if(in_array($v['store_category_id'],$bindList)){
                $v['disabled'] = true;
            }
        }
        $list =  formatCategory($list2, $dao->getPk());
        $ret =[];
        foreach ($list as $key => $value) {
            if (isset($value['children'])) {
                $level = [];
                foreach ($value['children'] as $child) {
                    if (isset($child['children'])) {
                        $level[] = $child;
                    }
                }
                if (isset($level) && !empty($level)) {
                    $value['children'] = $level;
                    $ret[] = $value;
                }
            }
        }
        $data['list'] = $ret;
        return app('json')->success($data);
    }

    public function getMarginQrCode($id)
    {
        $data['pay_type'] = 1;
        $data['id'] = $id;
        $res = app()->make(ServeOrderRepository::class)->QrCode($this->request->merId(), 'marginCategory', $data);
        return app('json')->success($res);
    }


    public function checkParams($validate)
    {
        $params = [
            ['lvl_one',''],
            ['lvl_two',''],
            ['mark', ''],
            ['images', ''],
        ];
        $data = $this->request->params($params);
        $validate->check($data);
        return $data;
    }
}
